package org.example.springkafka.POJO;


import com.alibaba.fastjson.JSON;
import org.apache.kafka.common.serialization.Serializer;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class UserSerializer implements Serializer<User> {
    @Override
    public byte[] serialize(String topic, User user) {
        // 简单暴力的方法
//       return JSON.toJSON(user).toString().getBytes(StandardCharsets.UTF_8);
       // 效率更高的方法
        byte[] bytes = user.getName().getBytes();
        int cap =  8 + bytes.length+4 + 4;
        ByteBuffer buffer = ByteBuffer.allocate(cap);
        buffer.putLong(user.getId());
        buffer.putInt(bytes.length);
        buffer.put(bytes);
        buffer.putInt(user.getSex());

        return buffer.array();

    }

}
